import { AppData } from "@/utils/app";
import { queryStringToObj } from "@/utils/object";

export const useQuery = <T>(
  option: MiniApp.AppLaunchOption,
  callback: (query: T) => void
) => {
  const fn = () => {
    let query: any = {};
    // 普通二维码扫码打开小程序
    if (option.q) {
      query = queryStringToObj(decodeURIComponent(option.q).split("?")[1]);
    } else {
      // 小程序码打开小程序
      query = Object.keys(option).reduce((obj, key) => {
        obj[key] = decodeURIComponent((option as any)[key]);
        return obj;
      }, {} as any);
    }
    // 渠道参数
    if (query.utm_tid) {
      AppData.bundleData.tagId = query.utm_tid;
    }

    console.log("AppLaunchOption", query);
    callback(query as T);
  };

  getCurrentPages().length === 1 ? useCheckSession(() => fn()) : fn();
};

export const useCheckSession = (callback: () => void) => {
  return uni.checkSession({
    success: () => {
      console.log("checkSession success");
      callback();
    },
    fail: error => {
      console.error("checkSession fail", error);
      // 登录态失效，删除用户信息
      AppData.deleteUserData();
      callback();
    },
  });
};
